'use strict'
const { NONAME } = require('dns')
const path = require('path')

function resolve(dir) {
  return path.join(__dirname, dir)
}
// let page = {
//   index: {
//     entry: 'src/main.js', // page 的入口
//     template: 'public/index.html', // 模板来源
//     filename: 'index.html', // 在 dist/index.html 的输出
//     // 当使用 title 选项时，template 中的 title 标签需要是 <title><%= htmlWebpackPlugin.options.title %></title>
//     title: 'Index Page',
//     // // 在这个页面中包含的块，默认情况下会包含,提取出来的通用 chunk 和 vendor chunk。
//     chunks: ['chunk-libs', 'chunk-elementUI', 'chunk-commons', 'index'],
//   },
//   redirect: {
//     entry: 'src/main.js',
//     template: 'public/redirect.html',
//     filename: 'redirect.html',
//     title: 'redirect Page',
//     chunks: ['chunk-libs', 'chunk-elementUI', 'chunk-commons', 'redirect'],
//   },
// }
module.exports = {
  assetsDir: 'static',
  // pages: page,
  lintOnSave: process.env.NODE_ENV === 'development',
  publicPath: './',
  devServer: {
    open: true,
    proxy: {
      '^/web': {
        target: process.env.VUE_APP_SERVER_FOUR_WHEEL_URL,
        changeOrigin: true,
      },
      '^/api-fourWheel': {
        target: process.env.VUE_APP_SERVER_FOUR_WHEEL_URL,
        changeOrigin: true,
        pathRewrite: {
          '^/api-fourWheel': '/hyc-3/web',
        },
        onProxyRes(proxyRes) {
          var cookies = proxyRes.headers['set-cookie']
          if (cookies == null || cookies.length == 0) {
            delete proxyRes.headers['set-cookie']
            return
          }
          for (var i = 0, n = cookies.length; i < n; i++) {
            if (cookies[i].match(/^JSESSIONID=[^;]+;[\s\S]*Path=\/[^;]+/)) {
              cookies[i] = cookies[i].replace(/Path=\/[^;]+/, 'Path=/')
            }
          }
          proxyRes.headers['set-cookie'] = cookies
        },
      },
      '^/api': {
        target: process.env.VUE_APP_SERVER_URL,
        changeOrigin: true,
        pathRewrite: {
          '^/api': '/hyc-3/web',
        },
        onProxyRes(proxyRes) {
          var cookies = proxyRes.headers['set-cookie']
          if (cookies == null || cookies.length == 0) {
            delete proxyRes.headers['set-cookie']
            return
          }
          for (var i = 0, n = cookies.length; i < n; i++) {
            if (cookies[i].match(/^JSESSIONID=[^;]+;[\s\S]*Path=\/[^;]+/)) {
              cookies[i] = cookies[i].replace(/Path=\/[^;]+/, 'Path=/')
            }
          }
          proxyRes.headers['set-cookie'] = cookies
        },
      },
    },
  },
  productionSourceMap: false,
  configureWebpack: {
    devtool: process.env.NODE_ENV === 'development' ? 'source-map' : 'none',
    performance: {
      hints: 'warning',
      // 入口起点的最大体积
      maxEntrypointSize: 1000000000,
      // 生成文件的最大体积
      maxAssetSize: 30000000,
      // 只给出 js 文件的性能提示
      assetFilter: function (assetFilename) {
        return assetFilename.endsWith('.js')
      },
    },
  },

  chainWebpack: (config) => {
    config.plugin('html').tap((args) => {
      args[0].title = '智能充电站管理后台'
      return args
    })
    config.plugins.delete('preload').delete('prefetch')

    config.resolve.symlinks(true)

    config.resolve.alias.set('@', resolve('src')).end()

    // config.module
    //   .rule('images')
    //   .use('image-webpack-loader')
    //   .loader('image-webpack-loader')
    //   .options({
    //     bypassOnDebug: true
    //   })
    //   .end()

    // set svg-sprite-loader
    config.module.rule('svg').exclude.add(resolve('src/icons')).end()
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]',
      })
      .end()

    config.module
      .rule('url')
      .test(/\.xlsx/)
      .use('url-loader')
      .loader('url-loader')
      .options({
        limit: 10000,
        name: 'static/template/[name]_[hash_7].[ext]',
        esModule: false,
      })
      .end()
    // set preserveWhitespace
    config.module
      .rule('vue')
      .use('vue-loader')
      .loader('vue-loader')
      .tap((options) => {
        options.compilerOptions.preserveWhitespace = true
        return options
      })
      .end()

    config.when(process.env.NODE_ENV === 'development', (config) =>
      config.devtool('cheap-source-map')
    )

    config.when(process.env.NODE_ENV !== 'development', (config) => {
      config
        .plugin('ScriptExtHtmlWebpackPlugin')
        .after('html')
        .use('script-ext-html-webpack-plugin', [
          {
            // `runtime` must same as runtimeChunk name. default is `runtime`
            inline: /runtime\..*\.js$/,
          },
        ])
        .end()
      config
        .plugin('CompressionWebpackPlugin')
        .use('compression-webpack-plugin')
        .tap(() => [
          {
            test: /\.js$|\.css$/,
            threshold: 10240,
            minRatio: 0.8,
          },
        ])
        .end()
      config.plugin('LodashWebpackPlugin').use('lodash-webpack-plugin').end()
      config.optimization.splitChunks({
        chunks: 'all',
        cacheGroups: {
          libs: {
            name: 'chunk-libs',
            test: /[\\/]node_modules[\\/]/,
            priority: 10,
            chunks: 'initial', // only package third parties that are initially dependent
          },
          elementUI: {
            name: 'chunk-elementUI', // split elementUI into a single package
            priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
            test: /[\\/]node_modules[\\/]_?element-ui(.*)/, // in order to adapt to cnpm
          },
          commons: {
            name: 'chunk-commons',
            test: resolve('src/components'), // can customize your rules
            minChunks: 3, //  minimum common number
            priority: 5,
            reuseExistingChunk: true,
          },
        },
      })
      config.optimization.runtimeChunk('single')
      // config.entry('main').add('babel-polyfill')
    })
  },
}
